/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.lyf.shop.controller;

import com.lyf.common.core.utils.StringUtils;
import com.lyf.common.core.web.controller.BaseController;
import com.lyf.common.redis.service.RedisService;
import com.lyf.shop.annotaton.AnonymousAccess;
import com.lyf.shop.annotaton.AnonymousGetMapping;
import com.lyf.shop.domain.Integral;
import com.lyf.shop.domain.Number;
import com.lyf.shop.domain.Order;
import com.lyf.shop.service.AliPayService;
import com.lyf.shop.service.IIntegralService;
import com.lyf.shop.service.INumberService;
import com.lyf.shop.service.IOrderService;
import com.lyf.shop.util.AliPayStatusEnum;
import com.lyf.shop.util.AlipayUtils;
import com.lyf.shop.vo.AlipayConfig;
import com.lyf.shop.vo.TradeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Map;


@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/aliPay")
@Api(tags = "工具：支付宝管理")
public class AliPayController extends BaseController {

    private final AlipayUtils alipayUtils;
    private final AliPayService alipayService;

    @Autowired
    private final AlipayConfig aliPay;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private INumberService numberService;

    @Autowired
    private IIntegralService integralService;


    @ApiOperation("PC网页支付")
    @PostMapping(value = "/toPayAsPC")
    public ResponseEntity<String> toPayAsPc(@RequestBody TradeVo trade) throws Exception {
        // 设置订单号
        trade.setOutTradeNo(alipayUtils.getOrderCode());
        String payUrl = alipayService.toPayAsPc(aliPay, trade);
        return ResponseEntity.ok(payUrl);
    }


    @ApiOperation("手机网页支付")
    @PostMapping(value = "/toPayAsWeb")
    public ResponseEntity<String> toPayAsWeb( @RequestBody TradeVo trade) throws Exception {
        // 设置订单号
        trade.setOutTradeNo(alipayUtils.getOrderCode());
        String payUrl = alipayService.toPayAsWeb(aliPay, trade);
        return ResponseEntity.ok(payUrl);
    }

    @ApiIgnore
    @AnonymousGetMapping("/return")
    @ApiOperation("支付之后跳转的链接")
    public ResponseEntity<String> returnPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=" + aliPay.getCharset());
        //内容验签，防止黑客篡改参数
        if (alipayUtils.rsaCheck(request, aliPay)) {
            //商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println("商户订单号" + outTradeNo + "  " + "第三方交易号" + tradeNo);

            Order order = orderService.selectOrderByOutTradeNo(outTradeNo);
            //request.getRequestDispatcher("/")
            // 根据业务需要返回数据，这里统一返回OK
           // response.setHeader("");
           // response.sendRedirect("localhost:80/order");
            return new ResponseEntity<>("payment successful", HttpStatus.OK);

        } else {
            // 根据业务需要返回数据
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    @ApiIgnore
    @RequestMapping("/notify")
    @AnonymousAccess
    @ApiOperation("支付异步通知(要公网访问)，接收异步通知，检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致，根据trade_status进行后续业务处理")
    public ResponseEntity<Object> notify(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        //内容验签，防止黑客篡改参数
        if (alipayUtils.rsaCheck(request, aliPay)) {
            //交易状态
            String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //付款金额
            String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //验证
            if (tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue()) || tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())) {
                // 支付宝回调，根据商户订单号获取订单信息，并修改订单成交状态。
                Order order = orderService.selectOrderByOutTradeNo(outTradeNo);
                if (StringUtils.isNotNull(order)){
                    //true 选择会员抵扣，false 跳过
                    if (order.getIntegralStatus().equals("0")){
                        // 获取会员的积分
                        Number number = numberService.selectNumberByNumberId(order.getNumberId());
                        Integral integral = new Integral();
                        BigDecimal numberIntegral = new BigDecimal(number.getIntegral());
                        BigDecimal divide = numberIntegral.divide(new BigDecimal(100), 2, 4);

                        BigDecimal amount = order.getAmount();
                        BigDecimal add = amount.add(divide);
                        // 原价设置成功
                        integral.setOriginalPrice(add);
                        integral.setIntegralTotal(number.getIntegral().toString());
                        integral.setPrice(amount);

                        integral.setMoney(add.subtract(order.getAmount()));
                        integral.setNumberId(order.getNumberId());
                        integral.setOrderId(order.getOrderId());
                        integral.setSupermarketId(order.getSupermarketId());
                        integralService.insertIntegral(integral);
                        //
                        Long longValue =order.getAmount().longValue();
                        number.setIntegral(longValue);
                        numberService.updateNumber(number);
                    }
                    order.setStatus(AliPayStatusEnum.OK.getValue());
                    order.setTradeNo(tradeNo);
                    orderService.updateOrder(order);
                    // 积分抵扣标志，如果不开启积分抵扣，则该会员增加积分
                    if (!order.getIntegralStatus().equals("0")) {
                        Number number = numberService.selectNumberByNumberId(order.getNumberId());
                        Long integral = number.getIntegral();
                        BigDecimal amount = order.getAmount();
                        long longValue = amount.longValue();
                        long sum = integral + longValue;
                        number.setIntegral(sum);
                        numberService.updateNumber(number);
                    }

                }
            }

            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
}
